package formal.array;

import java.util.HashMap;

/**
 * @author DengYuan2
 * @create 2021-02-08 19:24
 */
public class E_766 {
    public static void main(String[] args) {
//        int[][] nums = new int[][]{
//                {1, 2, 3, 4},
//                {5, 1, 2, 3},
//                {9, 5, 1, 2}
//        };

        int[][] nums = new int[][]
//                {
////                        {1, 2},
////                        {2, 2}
////                };
                {
                        {11, 74, 0, 93},
                        {40, 11, 74, 7}
                };


        boolean res = isToeplitzMatrix(nums);
        System.out.println(res);
    }

    /**
     * 我的写法-只检查第一行和第一列
     * 大神的思路和我的差不多
     * @param matrix
     * @return
     */
    public static boolean isToeplitzMatrix(int[][] matrix) {
        int row = matrix.length;
        int col = matrix[0].length;
        for (int i = 0; i < row; i++) {
            int j = 0;
            int num = matrix[i][j];
            int idx = i;
            while (idx < row && j < col) {
                if (matrix[idx++][j++] != num) {
                    return false;
                }
            }
        }
        for (int j = 1; j < col; j++) {
            int i = 0;
            int num = matrix[i][j];
            int idx = j;
            while (i < row && idx < col) {
                if (matrix[i++][idx++] != num) {
                    return false;
                }
            }
        }
        return true;
    }

    /**
     * 官方-检查左上角
     *
     * @param matrix
     * @return
     */
    public static boolean isToeplitzMatrix2(int[][] matrix) {
        for (int i = 1; i < matrix.length; i++) {
            for (int j = 1; j < matrix[0].length; j++) {
                if (matrix[i - 1][j - 1] != matrix[i][j]) {
                    return false;
                }
            }
        }
        return true;
    }

    /**
     * 官方-对角线法-不咋快，还是上面的左上角快一点
     * @param matrix
     * @return
     */
    public static boolean isToepliitzMatrix3(int[][] matrix){
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[0].length; j++) {
                if (!map.containsKey(i-j)){
                    map.put(i-j,matrix[i][j]);
                }else {
                    if (map.get(i-j)!=matrix[i][j]){
                        return false;
                    }
                }
            }
        }

        return true;
    }

}
